#include "frmmain.h"
#include "ui_frmmain.h"


// Application variables
QString APPNAME("dinky");
int CURRVER = 20130120;
QString APPVER("1.0");

// Application consumer key
std::string conKey("");
// Application consumer secret
std::string conSecret("");
// User access token key
std::string AccessTokenKey;
// User access token secret
std::string AccessTokenSecret;

frmMain::frmMain(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmMain)
{
    ui->setupUi(this);

    // A few extra bits and bobs required for the main QWebView component
    connect(ui->webView->page()->networkAccessManager(),
              SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )),
              this,
              SLOT(sslErrorHandler(QNetworkReply*, const QList<QSslError> & )));

    QPalette pal = ui->webView->palette();
    pal.setBrush(QPalette::Base, Qt::transparent);
    ui->webView->page()->setPalette(pal);
    ui->webView->setAttribute(Qt::WA_OpaquePaintEvent, false);
    ui->viewUserInfo->page()->setPalette(pal);
    ui->viewUserInfo->setAttribute(Qt::WA_OpaquePaintEvent, false);
    ui->webView->load(QUrl("http://www.matthewhipkin.co.uk/dinky-build/"));
    ui->webView->setContextMenuPolicy(Qt::NoContextMenu);
    ui->webView->setVisible(true);
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    // Check for, and open config file
    loadConfig();

    // Main update timer
    timerUpdate = new QTimer(this);
    timerUpdate->setInterval(60000);
    connect(timerUpdate,SIGNAL(timeout()),SLOT(OntimerUpdate()));

    if(AccessTokenKey == "" && AccessTokenSecret == "") {
        showAuthWin();
    }
    else OntimerUpdate();

}

frmMain::~frmMain()
{
    delete ui;
}

void frmMain::loadConfig()
{
    QDomDocument xml;
    QDomElement elem;
    QDomNode node;
    QDir appDir;

    appDir = QDir::homePath() + "/.dinky/";
    if(!appDir.exists()) appDir.mkdir(appDir.absolutePath());

    QFile xmlFile(appDir.filePath("dinky.conf"));

    if(xmlFile.open(QIODevice::ReadOnly)) {
      xml.setContent(&xmlFile);
      elem = xml.documentElement();
      node = elem.firstChild();
      while(!node.isNull()) {
        if(node.nodeName() == "token") AccessTokenKey = node.toElement().text().toStdString();
        if(node.nodeName() == "secret") AccessTokenSecret = node.toElement().text().toStdString();
        node = node.nextSibling();
      }
      xmlFile.close();
    }

}

void frmMain::saveConfig()
{
    QDir appDir;

    appDir = QDir::homePath() + "/.dinky/";
    if(!appDir.exists()) appDir.mkdir(appDir.absolutePath());

    QFile xmlFile(appDir.filePath("dinky.conf"));
    QString xml;

    xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    xml.append("<user>\n");
    xml.append("  <token>"+QString(AccessTokenKey.c_str())+"</token>\n");
    xml.append("  <secret>"+QString(AccessTokenSecret.c_str())+"</secret>\n");
    xml.append("</user>\n");

    if(xmlFile.open(QIODevice::WriteOnly)) {
        QTextStream outstream(&xmlFile);
        outstream << xml;
        xmlFile.close();
    }

}

QString frmMain::processText(const QString text)
{
    QStringList words = text.split(" ");
    QString tmp;
    for(int x=0;x<words.size();x++) {
        if(words.at(x).startsWith("http://")) {
            tmp = "<a href=\""+words.at(x)+"\" style=\"color: #FF5555\">"+words.at(x)+"</a>";
            words.replace(x,tmp);
        }
        if(words.at(x).startsWith("@")) {
            tmp = "<a href=\"#userprofile?username="+words.at(x)+"\" style=\"color: #5555FF\">"+words.at(x)+"</a>";
            words.replace(x,tmp);
        }
    }
    return words.join(" ");
}

void frmMain::showAuthWin()
{
    this->setFixedSize(640,400);
    connect(ui->webView, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));
    ui->webView->setUrl(QUrl("http://dinky-auth.matthewhipkin.co.uk/redirect.php"));
}

void frmMain::finishLoading(bool)
{
    if(ui->webView->url().toString().startsWith("http://dinky-auth.matthewhipkin.co.uk/callback.php",Qt::CaseInsensitive)) {
      this->setMaximumSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX);
      this->setMinimumSize(0,0);
      QString response = ui->webView->page()->currentFrame()->toHtml();
      QStringList resitems = response.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
      if(!response.isEmpty()) {

        int tokpos = resitems.indexOf("token=",0);
        int secpos = resitems.indexOf("secret=",0);
        for(int x=0;x<resitems.size();x++) {
            if(resitems.at(x).startsWith("token=")) tokpos = x;
            if(resitems.at(x).startsWith("secret=")) secpos = x;
        }
        AccessTokenKey = resitems.at(tokpos).split("=").last().toStdString();
        AccessTokenSecret = resitems.at(secpos).split("=").last().toStdString();
        saveConfig();
        OntimerUpdate();
      }
    }
}

void frmMain::refreshTimelines()
{
    twitCurl twitterObj;
    std::string response;
    twitterObj.getOAuth().setConsumerKey( conKey );
    twitterObj.getOAuth().setConsumerSecret( conSecret );
    twitterObj.getOAuth().setOAuthTokenKey( AccessTokenKey );
    twitterObj.getOAuth().setOAuthTokenSecret( AccessTokenSecret );
    if( twitterObj.accountVerifyCredGet() ) {
      twitterObj.getLastWebResponse(response);
      showUserInfo(response);
      if(twitterObj.timelineHomeGet()) {
        twitterObj.getLastWebResponse(response);
        homeXML = QString(response.c_str());
      }
      if(twitterObj.mentionsGet()) {
        twitterObj.getLastWebResponse(response);
        repliesXML = QString(response.c_str());
      }
      if(twitterObj.directMessageGet()) {
        twitterObj.getLastWebResponse(response);
        dmXML = QString(response.c_str());
      }
    }
}

void frmMain::showTimeline(QString tl)
{
    QString html;
    QDomDocument xml;
    QDomElement elem;
    QDomNode node;
    QDomNodeList l;
    QDomNodeList u;
    QString created_at;
    QString id;
    QString user_id;
    QString name;
    QString screen_name;
    QString profile_image_url;
    QString in_reply_to_status_id;
    QString in_reply_to_screen_name;
    QString text;
    QString source;

    if(tl == "home") xml.setContent(homeXML);
    if(tl == "replies") xml.setContent(repliesXML);
    if(tl == "dm") xml.setContent(dmXML);

    html = "<!doctype html>";
    html.append("<html>");
    html.append("<head>");
    html.append("<link href=\"http://fonts.googleapis.com/css?family=Shanti\" rel=\"stylesheet\" type=\"text/css\">");
    html.append("<style type=\"text/css\">");
    html.append("  body { background-color: transparent; font-family: Shanti; color: #FFFFFF }");
    html.append("  a { color: #FFFFFF }");
    html.append("  div {");
    html.append("    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(149,149,149,1)), color-stop(46%,rgba(13,13,13,1)), color-stop(50%,rgba(1,1,1,1)), color-stop(53%,rgba(10,10,10,1)), color-stop(76%,rgba(78,78,78,1)), color-stop(87%,rgba(56,56,56,1)), color-stop(100%,rgba(27,27,27,1)));");
    html.append("    background: -webkit-linear-gradient(top, rgba(149,149,149,1) 0%,rgba(13,13,13,1) 46%,rgba(1,1,1,1) 50%,rgba(10,10,10,1) 53%,rgba(78,78,78,1) 76%,rgba(56,56,56,1) 87%,rgba(27,27,27,1) 100%);");
    html.append("  }");
    html.append("</style>");
    html.append("<body>");
    //xml.setContent(QString(response.c_str()));
    elem = xml.documentElement();
    node = elem.firstChild();
    while(!node.isNull()) {
        if(node.nodeName() == "status") {
            l = node.childNodes();
            for(int i = 0; i < l.count(); i++) {
                if(l.item(i).nodeName() == "created_at") created_at = l.item(i).toElement().text();
                if(l.item(i).nodeName() == "id") id = l.item(i).toElement().text();
                if(l.item(i).nodeName() == "text") text = l.item(i).toElement().text();
                if(l.item(i).nodeName() == "source") source = l.item(i).toElement().text();
                if(l.item(i).nodeName() == "in_reply_to_status_id") in_reply_to_status_id = l.item(i).toElement().text();
                if(l.item(i).nodeName() == "in_reply_to_screen_name") in_reply_to_screen_name = l.item(i).toElement().text();
                if(l.item(i).nodeName() == "user") {
                    u = l.item(i).childNodes();
                    for(int x = 0; x < u.count(); x++) {
                        if(u.item(x).nodeName() == "id") user_id = u.item(x).toElement().text();
                        if(u.item(x).nodeName() == "name") name = u.item(x).toElement().text();
                        if(u.item(x).nodeName() == "screen_name") screen_name = u.item(x).toElement().text();
                        if(u.item(x).nodeName() == "profile_image_url") profile_image_url = u.item(x).toElement().text();
                    }
                }
            }
            html.append("<div style=\"width: 95%; border: 5px solid #000000; border-radius: 5px; padding: 3px;\">");
            html.append("<img src=\""+profile_image_url+"\" style=\"float: left\">");
            html.append("<p><b>"+screen_name+"</b></p>");
            html.append("<p style=\"font-size: 9pt\">"+processText(text)+"</p>");
            html.append("<small>"+created_at+" via "+source+"</small><a href=\"#reply?sn=&id\"><span style=\"float: right; background-color: transparent\"><img src=\"http://www.matthewhipkin.co.uk/res/reply.png\" border=\"0\"></a> <a href=\"\"><img style=\"float:right\" src=\"http://www.matthewhipkin.co.uk/res/favorite.png\"></a><a href=\"\"><img style=\"float:right\" src=\"http://www.matthewhipkin.co.uk/res/retweet.png\"></a></span>");
            html.append("</div>");
            html.append("&nbsp;");
        }
        node = node.nextSibling();
    }
    html.append("</body>");
    html.append("</html>");
    ui->webView->setHtml(html);
}

void frmMain::OntimerUpdate()
{
    timerUpdate->stop();
    // Main refresh routine here
    refreshTimelines();
    if(ui->btnHome->isChecked()) showTimeline("home");
    if(ui->btnReplies->isChecked()) showTimeline("replies");
    if(ui->btnDM->isChecked()) showTimeline("dm");
   // timerUpdate->start();
}

void frmMain::sslErrorHandler(QNetworkReply* qnr, const QList<QSslError> & errlist)
{
  qnr->ignoreSslErrors();
}

void frmMain::on_btnAbout_clicked()
{
    QString html;
    html = "<p><b style=\"font-size: 14pt\">"+APPNAME+"</b> "+APPVER+"<br>\n";
    html.append("&copy;2012, 2013 Matthew Hipkin<br>\n");
    html.append("<a href=\"http://www.matthewhipkin.co.uk\" style=\"color: #FF0000\">http://www.matthewhipkin.co.uk</a></p>\n");
    html.append("<p>A small, easy to use desktop twitter client</p>");
    html.append("<p>Follow me on twitter <a href=\"http://twitter.com/hippy2094\" style=\"color: #FF0000\">@hippy2094</a></p>");
    QMessageBox::about(this,"About dinky",html);
}

void frmMain::on_webView_linkClicked(const QUrl &arg1)
{
    if(arg1.toString().startsWith("http://")) QDesktopServices::openUrl(arg1);
    else {
        if(arg1.toString().startsWith("#userprofile")) {

        }
    }
}

void frmMain::showUserInfo(std::string response)
{
    QString html;
    QString username;
    QString displayname;
    QString followcount;
    QString followercount;
    QString tweetcount;
    QString image_profile_url;
    QDomDocument xml;
    QDomElement elem;
    QDomNode node;
    QDomNodeList l;

    xml.setContent(QString(response.c_str()));
    elem = xml.documentElement();
    node = elem.firstChild();
    while(!node.isNull()) { // toElement().text();
      if(node.nodeName() == "name") displayname = node.toElement().text();
      if(node.nodeName() == "screen_name") username = node.toElement().text();
      if(node.nodeName() == "profile_image_url") image_profile_url = node.toElement().text();
      if(node.nodeName() == "followers_count") followercount = node.toElement().text();
      if(node.nodeName() == "friends_count") followcount = node.toElement().text();
      if(node.nodeName() == "statuses_count") tweetcount = node.toElement().text();
      node = node.nextSibling();
    }

    html = "<!doctype html>\n";
    html.append("<html>");
    html.append("<head>");
    html.append("<link href=\"http://fonts.googleapis.com/css?family=Shanti\" rel=\"stylesheet\" type=\"text/css\">");
    html.append("<style type=\"text/css\">");
    html.append("  body { background-color: transparent; font-family: Shanti; font-size: 8pt; color: #FFFFFF; margin: 0px; overflow: hidden }");
    html.append("  div {");
    html.append("    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(149,149,149,1)), color-stop(46%,rgba(13,13,13,1)), color-stop(50%,rgba(1,1,1,1)), color-stop(53%,rgba(10,10,10,1)), color-stop(76%,rgba(78,78,78,1)), color-stop(87%,rgba(56,56,56,1)), color-stop(100%,rgba(27,27,27,1)));");
    html.append("    background: -webkit-linear-gradient(top, rgba(149,149,149,1) 0%,rgba(13,13,13,1) 46%,rgba(1,1,1,1) 50%,rgba(10,10,10,1) 53%,rgba(78,78,78,1) 76%,rgba(56,56,56,1) 87%,rgba(27,27,27,1) 100%);");
    html.append("  }");
    html.append("</style>");
    html.append("</head>");
    html.append("<body>");
    html.append("<div style=\"float: right; border: 3px solid #000000; border-radius: 3px; padding: 8px\">");
    html.append("<img src=\""+image_profile_url+"\" style=\"float: left\">");
    html.append("<b>"+username+"</b><br>");
    html.append("<nobr>"+tweetcount + " tweets</nobr><br>");
    html.append("<nobr>" + followercount + " followers</nobr><br><nobr>" + followcount + " following</nobr>");
    html.append("</div>");
    html.append("</body>");
    html.append("</html>");
    ui->viewUserInfo->setHtml(html);
}

void frmMain::on_btnHome_clicked()
{
    ui->btnHome->setChecked(true);
    ui->btnDM->setChecked(false);
    ui->btnReplies->setChecked(false);
    showTimeline("home");
}

void frmMain::on_btnReplies_clicked()
{
    ui->btnHome->setChecked(false);
    ui->btnDM->setChecked(false);
    ui->btnReplies->setChecked(true);
    showTimeline("replies");
}

void frmMain::on_btnDM_clicked()
{
    ui->btnHome->setChecked(false);
    ui->btnDM->setChecked(true);
    ui->btnReplies->setChecked(false);
    showTimeline("dm");
}

void frmMain::on_lineEdit_returnPressed()
{
    twitCurl twitterObj;
    std::string response;
    twitterObj.getOAuth().setConsumerKey( conKey );
    twitterObj.getOAuth().setConsumerSecret( conSecret );
    twitterObj.getOAuth().setOAuthTokenKey( AccessTokenKey );
    twitterObj.getOAuth().setOAuthTokenSecret( AccessTokenSecret );

    std::string msg;
    msg = ui->lineEdit->text().toStdString();
    if(twitterObj.statusUpdate(msg,reply_to_id)) {
      twitterObj.getLastWebResponse(response);
      reply_to_id = "";
      ui->lineEdit->setText("");
      qDebug(response.c_str());
    }


}

void frmMain::on_btnHelp_clicked()
{

}
